# -*- coding: utf-8 -*-
"""
HTML表格组件测试示例 - 包含内嵌图表功能
"""
import sys
import os
# 添加项目根目录到Python路径
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', '..', '..'))

from PySide6.QtWidgets import QApplication, QMainWindow, QVBoxLayout, QWidget, QPushButton, QHBoxLayout
from ui.components.charts.html_table import TgHtmlTable
import random


class HtmlTableDemo(QMainWindow):
    """HTML表格演示窗口"""
    
    def __init__(self):
        super().__init__()
        self.setWindowTitle("HTML表格组件测试 - 带走势图")
        self.setGeometry(100, 100, 1200, 700)
        
        # 创建中心部件
        central_widget = QWidget()
        self.setCentralWidget(central_widget)
        
        # 创建布局
        layout = QVBoxLayout(central_widget)
        
        # 创建按钮布局
        button_layout = QHBoxLayout()
        
        # 创建按钮
        self.load_sample_btn = QPushButton("加载示例数据")
        self.profit_loss_btn = QPushButton("设置盈亏样式")
        self.chart_btn = QPushButton("设置走势图")
        self.toggle_sort_btn = QPushButton("切换排序")
        self.add_row_btn = QPushButton("添加行")
        self.clear_btn = QPushButton("清空数据")
        
        button_layout.addWidget(self.load_sample_btn)
        button_layout.addWidget(self.profit_loss_btn)
        button_layout.addWidget(self.chart_btn)
        button_layout.addWidget(self.toggle_sort_btn)
        button_layout.addWidget(self.add_row_btn)
        button_layout.addWidget(self.clear_btn)
        button_layout.addStretch()
        
        # 创建HTML表格
        self.html_table = TgHtmlTable()
        
        # 添加到布局
        layout.addLayout(button_layout)
        layout.addWidget(self.html_table)
        
        # 连接信号
        self.load_sample_btn.clicked.connect(self.load_sample_data)
        self.profit_loss_btn.clicked.connect(self.set_profit_loss_style)
        self.chart_btn.clicked.connect(self.set_chart_column)
        self.toggle_sort_btn.clicked.connect(self.toggle_sorting)
        self.add_row_btn.clicked.connect(self.add_sample_row)
        self.clear_btn.clicked.connect(self.clear_data)
        
        # 初始加载数据
        self.load_sample_data()
        # 自动设置图表列
        self.set_chart_column()
    
    def load_sample_data(self):
        """加载示例数据"""
        headers = ["股票代码", "股票名称", "最新价", "涨跌幅", "涨跌额", "近期走势", "成交量", "成交额"]
        
        # 生成包含走势数据的示例数据
        data = []
        stocks = [
            ("000001", "平安银行", 12.50, 2.35, 0.29),
            ("000002", "万科A", 25.80, -1.20, -0.31),
            ("000858", "五粮液", 158.90, 3.45, 5.30),
            ("000876", "新希望", 18.20, -2.15, -0.40),
            ("600519", "贵州茅台", 1950.00, 1.85, 35.40),
            ("600036", "招商银行", 42.60, -0.50, -0.21),
            ("000858", "腾讯控股", 385.20, 4.20, 15.50),
        ]
        
        for code, name, price, change_pct, change_amt in stocks:
            # 生成近期走势数据（10个交易日的价格）
            trend_data = self.generate_trend_data(price, change_pct, 10)
            trend_str = ",".join([f"{x:.2f}" for x in trend_data])
            
            volume = f"{random.randint(50, 500)}.{random.randint(0, 9)}万"
            amount = f"{random.randint(1, 50)}.{random.randint(0, 99)}亿"
            
            row = [code, name, f"{price:.2f}", f"{change_pct:+.2f}%", f"{change_amt:+.2f}", 
                   trend_str, volume, amount]
            data.append(row)
        
        self.html_table.update_data(headers, data)
        print("示例数据已加载，走势数据示例：")
        print(f"第一行走势数据: {data[0][5]}")
    
    def generate_trend_data(self, current_price, final_change_pct, days=10):
        """生成模拟的走势数据"""
        # 从当前价格往回推算历史价格
        prices = []
        price = current_price
        
        # 生成随机的日涨跌幅
        daily_changes = []
        remaining_change = final_change_pct
        
        for i in range(days - 1):
            # 随机生成一个涨跌幅，但要考虑总体趋势
            daily_change = random.uniform(-3, 3)
            if abs(remaining_change) > 1:
                # 如果还有较大的剩余变化，倾向于朝目标方向变化
                if remaining_change > 0:
                    daily_change = abs(daily_change) * random.choice([1, -0.3])
                else:
                    daily_change = -abs(daily_change) * random.choice([1, -0.3])
            
            daily_changes.append(daily_change)
            remaining_change -= daily_change
        
        # 最后一天的变化确保达到目标
        daily_changes.append(remaining_change)
        
        # 计算历史价格
        for i in range(days - 1, -1, -1):
            if i == days - 1:
                prices.append(current_price)
            else:
                prev_price = prices[0]
                # 计算前一天的价格
                historical_price = prev_price / (1 + daily_changes[i] / 100)
                prices.insert(0, historical_price)
        
        return prices
    
    def set_profit_loss_style(self):
        """设置盈亏样式"""
        # 对"涨跌幅"和"涨跌额"列应用盈亏样式
        self.html_table.set_profit_loss_style([3, 4], use_gradient=True, color_type='background')  # 列索引
        self.profit_loss_btn.setText("盈亏样式已设置")
        print("盈亏样式已设置到列 3, 4")
    
    def set_chart_column(self):
        """设置图表列"""
        # 对"近期走势"列设置图表显示
        chart_config = {
            'width': 120,
            'height': 35,
            'positive_color': '#f44336',  # 红色上涨
            'negative_color': '#4caf50',  # 绿色下跌
            'show_percent': False
        }
        try:
            self.html_table.set_chart_column(5, chart_config)  # 使用索引5对应"近期走势"列
            self.chart_btn.setText("走势图已设置")
            print("走势图已设置到列 5")
        except Exception as e:
            print(f"设置图表列时出错: {e}")
    
    def toggle_sorting(self):
        """切换排序功能"""
        current_state = self.html_table._sorting_enabled
        self.html_table.enable_sorting(not current_state)
        status = "启用" if not current_state else "禁用"
        self.toggle_sort_btn.setText(f"排序已{status}")
    
    def add_sample_row(self):
        """添加示例行"""
        codes = ["300750", "002415", "000725", "600588"]
        names = ["宁德时代", "海康威视", "京东方A", "用友网络"]
        
        code = random.choice(codes)
        name = random.choice(names)
        price = round(random.uniform(10, 200), 2)
        change_pct = round(random.uniform(-5, 5), 2)
        change_amt = round(price * change_pct / 100, 2)
        
        # 生成走势数据
        trend_data = self.generate_trend_data(price, change_pct, 10)
        trend_str = ",".join([f"{x:.2f}" for x in trend_data])
        
        volume = f"{random.randint(50, 500)}.{random.randint(0, 9)}万"
        amount = f"{random.randint(1, 50)}.{random.randint(0, 99)}亿"
        
        new_row = [code, name, f"{price:.2f}", f"{change_pct:+.2f}%", f"{change_amt:+.2f}", 
                   trend_str, volume, amount]
        self.html_table.add_row(new_row)
        print(f"添加新行，走势数据: {trend_str}")
    
    def clear_data(self):
        """清空数据"""
        self.html_table.clear_data()


def main():
    app = QApplication(sys.argv)
    
    # 创建演示窗口
    demo = HtmlTableDemo()
    demo.show()
    
    sys.exit(app.exec())


if __name__ == "__main__":
    main()